package com.yzh.openai.trigger.http;

import com.alibaba.fastjson.JSON;
import com.google.common.eventbus.EventBus;
import com.yzh.lantu.common.Transaction;
import com.yzh.openai.domain.auth.service.IAuthService;
import com.yzh.openai.domain.order.model.entity.PayOrderEntity;
import com.yzh.openai.domain.order.model.entity.ProductEntity;
import com.yzh.openai.domain.order.model.entity.ShopCartEntity;
import com.yzh.openai.domain.order.model.valobj.LanTuNotifyVO;
import com.yzh.openai.domain.order.service.IOrderService;
import com.yzh.openai.trigger.http.dto.SaleProductDTO;
import com.yzh.openai.trigger.mq.producer.RedisPublisher;
import com.yzh.openai.types.common.Constants;
import com.yzh.openai.types.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}/sale")
public class SaleController {
    @Resource
    private IOrderService orderService;
    @Resource
    private IAuthService authService;
    @Resource
    private RedisPublisher publisher;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询商品列表
     *
     * @return
     */
    @GetMapping("/query_product_list")
    public Response<List<SaleProductDTO>> queryProductList() {
        try {
            //1.查询商品
            List<ProductEntity> productEntityList = orderService.queryProductList();

            //2.封装返回结果
            List<SaleProductDTO> saleProductDTOList = new ArrayList<SaleProductDTO>();
            for (ProductEntity productEntity : productEntityList) {
                SaleProductDTO saleProductDTO = SaleProductDTO.builder()
                        .productId(productEntity.getProductId())
                        .productName(productEntity.getProductName())
                        .productDesc(productEntity.getProductDesc())
                        .quota(productEntity.getQuota())
                        .price(productEntity.getPrice())
                        .build();
                saleProductDTOList.add(saleProductDTO);
            }
            return Response.success(saleProductDTOList);
        } catch (Exception e) {
            log.error("商品查询失败", e);
            return Response.error(Constants.ResponseCode.UN_ERROR);
        }
    }

    /**
     * 用户下单商品
     *
     * @param productId
     * @return
     */
    @PostMapping("/create_pay_order")
    public Response<String> createParOrder(@RequestParam Integer productId, @RequestHeader("Authorization") String token) {
        try {
            //1.Token解析
            String openid = authService.getOpenid(token);
            assert null != openid;
            log.info("商品下单开始，创建订单 openid：{} productId：{}", openid, productId);
            //2.下单
            ShopCartEntity shopCartEntity = ShopCartEntity.builder()
                    .openid(openid)
                    .productId(productId)
                    .build();
            PayOrderEntity payOrder = orderService.createOrder(shopCartEntity);
            log.info("商品下单结束，待支付 openid：{} productId：{} payOrder：{}", openid, productId, payOrder);
            return Response.success(payOrder.getPayUrl());
        } catch (Exception e) {
            log.error("商品下单失败", e);
            return Response.error(Constants.ResponseCode.UN_ERROR);
        }
    }

    /**
     * 支付回调(蓝兔支付微信)
     *
     * @param notifyVO
     * @param response
     * @throws IOException
     */
    @PostMapping("/pay_notify")
    public void payNotify(LanTuNotifyVO notifyVO, HttpServletResponse response) throws IOException {
        try {
            //将支付成功的回调信息转换为Transaction
            if (Transaction.PayCode.SUCCESS.getCode().toString().equals(notifyVO.getCode())) {
                //商户订单号
                String orderId = notifyVO.getOut_trade_no();
                //蓝兔支付系统订单号
                String transactionId = notifyVO.getOrder_no();
                BigDecimal totalAmount = new BigDecimal(notifyVO.getTotal_fee());
                String successTime = notifyVO.getSuccess_time();
                log.info("支付成功 orderId：{} total：{} successTime：{}", orderId, totalAmount, successTime);
                //更新订单
                boolean success = orderService.changeOrderPaySuccess(orderId, transactionId, totalAmount, dateFormat.parse(successTime));
                if (success) {
                    //发送消息去发货
                    publisher.publishOrder(orderId);
                }
                response.getWriter().write("SUCCESS");
            } else {
                response.getWriter().write("FAIL");
            }
        } catch (Exception e) {
            log.error("支付失败", e);
            response.getWriter().write("FAIL");
        }
    }
}
